#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

int sockfd;//返回的套接字
struct sockaddr_in Rose_addr ;//Rose的地址
int size = sizeof(struct sockaddr_in );

//线程回调函数
void * func (void * arg)
{
    char * Jack_send_msg = calloc(128,1);
    int Jack_send_byte = -1;

    while(1)
    {
        printf("Jack 请输入要发送的信息:\n");
        fgets(Jack_send_msg,128,stdin);
        
        Jack_send_byte = sendto(sockfd, Jack_send_msg, strlen(Jack_send_msg) , 0 , (struct sockaddr *)&Rose_addr, size);
        if(Jack_send_byte == -1)
        {
            perror("Jcak recvive fail\n");
            continue;
        }
        else
        {
            printf("Jack成功发送信息,共%d个字节\n",Jack_send_byte);
        }
        
    }

    return 0;

}


int main(int argc, char const *argv[])
{
    //建立网络接口（油箱）
    sockfd = socket(AF_INET, SOCK_DGRAM , 0);//返回待连接套接字
    if(sockfd == -1)
    {
        perror("Jack socket fail\n");
        return -1;
    }

    //设置IP地址以及端口号
    // struct sockaddr_in {
    // sa_family_t     sin_family;     /* AF_INET */
    // in_port_t       sin_port;       /* Port number */
    // struct in_addr  sin_addr;       /* IPv4 address */
    // };

    struct sockaddr_in my_addr = {0};
    my_addr.sin_family = AF_INET;  //网络簇 IPV4协议
    my_addr.sin_port = htons(65000);//设置网络端口号，并且转化网络字节序二进制
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);//当前服务端下所有IP地址均能够接受信息


    //绑定油箱和地址
    int retval  = bind(sockfd, (struct sockaddr *)&my_addr,size);
    if(retval)
    {
        perror("bind fail\n");
        return -1;
    }

    //创建线程进行发送信息
    pthread_t Tid;
    int ret = pthread_create(&Tid,NULL,func,NULL);
    if(ret)
    {
        fprintf(stderr,"pthread_create error:%s",strerror(ret)); //打印出错误原因
        close(sockfd);
        return -1;
    }


    //坐等接受信息
    char * rev_msg = calloc(128,1);
    
    while(1)
    {
       
        printf("Jack等待消息进来\n");
        int rec_byte = recvfrom(sockfd, rev_msg, 128 , 0 , (struct sockaddr *)&Rose_addr,&size);
        if(rec_byte == -1)
        {
            perror("recvive fail\n");
            return 0;
        }
        else
        {
            printf("Rose_IP = %s port=%d\n ",inet_ntoa(Rose_addr.sin_addr),ntohs(Rose_addr.sin_port));
            printf("Jack成功接收的信息:%s 共%d个字节",rev_msg,rec_byte);
        }
        
    }

    //关闭套接字文件
    close(sockfd);

    return 0;
}

